<template>
  <div class="container">
    <!-- 二级分类面包屑 -->
    <SubBreadcrumb />
    <!-- 筛选区 -->
    <SubFilter @filter-change="filterChange" />
    <!-- 复选框 -->
    <!-- <XtxCheckbox v-model="isAllCheck">全部</XtxCheckbox>{{ isAllCheck }} -->
    <div class="goods-list">
      <!-- 排序 -->
      <SubSort @sort-change="sortChange" />
      <!-- 列表 -->
      <ul>
        <li v-for="goods in goodsList" :key="goods.id">
          <GoodsItem :goods="goods" />
        </li>
      </ul>
      <!-- 加载更多 -->
      <XtxInfiniteLoading
        :loading="loading"
        :finished="finished"
        @infinite="getData"
      />
    </div>
  </div>
</template>

<script>
import SubBreadcrumb from './components/sub-breadcrumb'
import SubFilter from './components/sub-filter'
import SubSort from './components/sub-sort'
import GoodsItem from './components/goods-item'
import { ref, watch } from 'vue'
import { findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'
export default {
  components: {
    SubBreadcrumb,
    SubFilter,
    SubSort,
    GoodsItem
  },
  setup () {
    const loading = ref(false)
    const finished = ref(false)
    const goodsList = ref([])

    let reqParams = {
      // 查询参数
      page: 1,
      pageSize: 20
    }

    const route = useRoute()

    const getData = () => {
      const categoryId = route.params.id
      reqParams.categoryId = categoryId

      // 开始加载
      loading.value = true
      findSubCategoryGoods(reqParams).then(({ result }) => {
        // 有数据
        if (result.items.length) {
          goodsList.value.push(...result.items)

          reqParams.page++
        } else {
          // 没有数据了
          finished.value = true
        }

        // 加载完毕
        loading.value = false
      })
    }

    watch(
      () => route.params.id,
      newVal => {
        // 二级分类切换了
        if (newVal && `/category/sub/${newVal}` === route.path) {
          reqParams = {
            // 查询参数
            page: 1,
            pageSize: 20
          }

          finished.value = false
          goodsList.value = []
        }
      }
    )

    // 排序改变了
    const sortChange = sortParams => {
      reqParams = { ...reqParams, ...sortParams }
      reqParams.page = 1

      finished.value = false
      goodsList.value = []
    }

    const filterChange = filterParams => {
      if (!filterParams.attrs) filterParams.attrs = null

      reqParams = { ...reqParams, ...filterParams }
      reqParams.page = 1

      finished.value = false
      goodsList.value = []
    }

    return {
      getData,
      loading,
      finished,
      goodsList,
      sortChange,
      filterChange
    }
  }
}
</script>

<style scoped lang="less">
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
